/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.fzhucc.modules.sciCp.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.sciCp.domain.Cp;
import com.fzhucc.modules.sciCp.domain.dto.CpAddEditDto;
import com.fzhucc.modules.sciTechnologyDemand.domain.dto.SciTechnologyDemandDto;
import com.fzhucc.modules.sciTechnologyDemand.domain.dto.SciTechnologyDemandQueryCriteria;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.sciCp.repository.CpRepository;
import com.fzhucc.modules.sciCp.domain.dto.CpDto;
import com.fzhucc.modules.sciCp.domain.dto.CpQueryCriteria;
import com.fzhucc.modules.sciCp.service.mapstruct.CpMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author yyg
* @date 2024-03-07
**/
@Service
@RequiredArgsConstructor
public class CpService {

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    private final UserRepository userRepository;

    private final CpRepository cpRepository;
    private final CpMapper cpMapper;

    public Map<String,Object> queryAll(CpQueryCriteria criteria, Pageable pageable){
        //管理端根据登录用户地区
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            } else {
                criteria.setOrgArea(str);
            }
        } else {
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length == 3) {
                if (str.contains(criteria.getOrgAreas()[1])) {
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            } else {
                criteria.setOrgArea(str);
            }
        }
        criteria.setOrgAreas(null);
        Page<Cp> page = cpRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Page<CpDto> map = page.map(cpMapper::toDto);
        List<CpDto> list = map.getContent();
        if (list!=null && list.size()>0){
            for (CpDto dto : list) {
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }

                String pic = dto.getPic();
                if (pic != null && pic.contains(";")) {
                    String[] array = pic.split(";");
                    dto.setPics(array);
                } else {
                    String[] array = {};
                    dto.setPics(array);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public Map<String,Object> queryAllh5(CpQueryCriteria criteria, Pageable pageable){
        //管理端根据登录用户地区
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            } else {
                criteria.setOrgArea(str);
            }
        } else {
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length == 3) {
                if (str.contains(criteria.getOrgAreas()[1])) {
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            } else {
                criteria.setOrgArea(str);
            }
        }
        criteria.setOrgAreas(null);
        Page<Cp> page = cpRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Page<CpDto> map = page.map(cpMapper::toDto);
        List<CpDto> list = map.getContent();
        if (list!=null && list.size()>0){
            for (CpDto dto : list) {
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }

                String pic = dto.getPic();
                if (pic != null && pic.contains(";")) {
                    String[] array = pic.split(";");
                    dto.setPics(array);
                } else {
                    String[] array = {};
                    dto.setPics(array);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public List<CpDto> queryAll(CpQueryCriteria criteria){
        //导出  如果有传则按传的数组 导出
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            } else {
                criteria.setOrgArea(str);
            }
        } else {
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length == 3) {
                if (str.contains(criteria.getOrgAreas()[1])) {
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            } else {
                criteria.setOrgArea(str);
            }
        }
        return cpMapper.toDto(cpRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    //根据不同设置不同的部门查看
    public String setCriteria(CpQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && (orgArea.equals(all) || orgArea.equals(all2))) { //如果等于福建省则查全部
                return null;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//用的org组织最高看全部
                return null;
            } else {
                return res.getOrgArea();//如果用户的权限不是福建省则 只能看到对应的组织
            }
        } else {
            return null;
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            return res.getOrgArea();
        }
    }

    @Transactional
    public CpDto findById(Integer id) {
        Cp cp = cpRepository.findById(id).orElseGet(Cp::new);
        ValidationUtil.isNull(cp.getId(),"Cp","id",id);
        CpDto dto = cpMapper.toDto(cp);

        String orgArea = dto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            dto.setOrgAreas(array);
        } else {
            String[] array = {};
            dto.setOrgAreas(array);
        }

        String pic = dto.getPic();
        if (pic != null && pic.contains(";")) {
            String[] array = pic.split(";");
            dto.setPics(array);
        } else {
            String[] array = {};
            dto.setPics(array);
        }
        return dto;
    }

    @Transactional(rollbackFor = Exception.class)
    public CpDto create(CpAddEditDto dto) {
        Cp resources = new  Cp();
        String name = dto.getName();
        if (name == null) {
            throw new BadRequestException("产品名称为空");
        }
        resources.setName(name);
        resources.setIsShow(dto.getIsShow());
        resources.setCover(dto.getCover());
        resources.setSort(dto.getSort());
        resources.setIntroduce(dto.getIntroduce());
        resources.setSource(dto.getSource());
        if (dto.getPics() != null && dto.getPics().length > 0) {
            String last = "";
            for (String a : dto.getPics()) {
                last = last + a + ";";
            }
            resources.setPic(last);
        } else {
            resources.setPic(null);
        }
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }
        Cp save = cpRepository.save(resources);
        CpDto cpDto = cpMapper.toDto(save);

        String orgArea = cpDto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            dto.setOrgAreas(array);
        } else {
            String[] array = {};
            dto.setOrgAreas(array);
        }

        String pic = cpDto.getPic();
        if (pic != null && pic.contains(";")) {
            String[] array = pic.split(";");
            dto.setPics(array);
        } else {
            String[] array = {};
            dto.setPics(array);
        }
        return cpDto;
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(CpAddEditDto resources) {
        Cp cp = cpRepository.findById(resources.getId()).orElseGet(Cp::new);
        ValidationUtil.isNull( cp.getId(),"Cp","id",resources.getId());
        if (resources.getOrgAreas() != null && resources.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : resources.getOrgAreas()) {
                last = last + a + ";";
            }
            cp.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            cp.setOrgArea(orgAreaReturn());
        }
        if (resources.getPics() != null && resources.getPics().length > 0) {
            String last = "";
            for (String a : resources.getPics()) {
                last = last + a + ";";
            }
            cp.setPic(last);
        } else {
            cp.setPic(null);
        }
        cp.setCover(resources.getCover());
        cp.setIntroduce(resources.getIntroduce());
        cp.setSort(resources.getSort());
        cp.setName(resources.getName());
        cp.setSource(resources.getSource());
        cp.setIsShow(resources.getIsShow());
        cpRepository.save(cp);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            cpRepository.deleteById(id);
        }
    }

    public void download(List<CpDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CpDto cp : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("产品名称", cp.getName());
            map.put("项目来源", cp.getSource());
            map.put("介绍", cp.getIntroduce());
            map.put("图片多张 ;", cp.getPic());
            map.put("封面", cp.getCover());
            map.put("排序", cp.getSort());
            map.put("是否展示", cp.getIsShow());
            String orgArea = cp.getOrgArea();
            if (orgArea != null) {
                if (orgArea.contains(";")) {
                    String[] split = orgArea.split(";");
                    String str = "";
                    for (String a : split) {
                        str = str + a + "/";
                    }
                    map.put("所属工会", str);
                } else {
                    map.put("所属工会", orgArea);
                }
            } else {
                map.put("所属工会", "");
            }
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}